package com.atguigu.gulimall.ware.consumer;

import com.atguigu.common.mq.OrderTo;
import com.atguigu.common.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author dengchujun
 * @Description
 * @date 2024/6/13
 */
@Slf4j
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;


    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel){
        log.info("接受到的库存锁定信息,message={}",message);
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            log.error("库存锁定消息，消费失败,message={}",message);
        }

    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel){
        log.info("订单关闭库存锁定信息,message={}",message);
        try {
            wareSkuService.unlockStockOrderHandle(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            log.error("订单关闭库存锁定信息，消费失败,message={}",message);
        }
    }

}
